package middleware

import (
	"github.com/flosch/pongo2"
	"github.com/gin-gonic/gin"
	"net/http"
	"reflect"
	"yak.admin/src/entity"
	"yak.admin/src/util"
)

const (
	success = iota
	fail
	refuse
)

type Page struct {
	Title string
	Linker string
	Header string
	Tpl string
	Data map[string]interface{}
}

func ResponseMiddle() gin.HandlerFunc{
	return func(c *gin.Context) {
		c.Next()
		if page, ok := c.Get("Page"); ok {
			if reflect.TypeOf(page).String() == "string" {
				RenderData(c, Page{Tpl: page.(string)})
				return
			}
			RenderData(c, page.(Page))
			return
		}
	}
}

func ResultSuccess(c *gin.Context, msg string, data map[string]interface{}) {
	if data == nil {
		c.JSON(http.StatusOK, map[string]interface{} { "code": success, "msg": msg, })
	} else {
		c.JSON(http.StatusOK, map[string]interface{} { "code": success, "msg": msg, "data": data,})
	}
}

func ResultFail(c *gin.Context, msg string, data map[string]interface{}) {
	if data == nil {
		c.JSON(http.StatusOK, map[string]interface{} { "code": fail, "msg": msg, })
	} else {
		c.JSON(http.StatusOK, map[string]interface{} { "code": fail, "msg": msg, "data": data,})
	}
}

func ResultRefuse(c *gin.Context, msg string, data map[string]interface{}) {
	c.JSON(http.StatusOK, map[string]interface{} {
		"code": refuse, "msg": msg, "data": data,
	})
}

func RenderData(c *gin.Context, page Page) {
	var data pongo2.Context
	if page.Data == nil {
		data = make(pongo2.Context)
	} else {
		data = page.Data
	}
	data["Title"] = page.Title
	data["Linker"] = page.Linker
	data["Header"] = page.Header
	if admin, exist := c.Get(util.AdminKey); exist {
		u := admin.(entity.Admin)
		data["Admin"] = u
		data["IsSuper"] = u.IsSuper()
	}
	data["Company"] = util.GetSettingValue("company")
	c.HTML(http.StatusOK, page.Tpl, data)
}

func Datalist(c *gin.Context, data interface{}, num int64)  {
	c.JSON(http.StatusOK, map[string]interface{} {
		"code": success, "msg": "success", "data": data, "count": num,
	})
}

func DataExcel(c *gin.Context, data interface{}, header interface{})  {
	c.JSON(http.StatusOK, map[string]interface{} {
		"code": success, "msg": "success", "data": data, "header": header,
	})
}
